//
//  WeAuctionPublishContentCell.m
//  WeGalaxy
//
//  Created by Zheng on 2017/6/30.
//  Copyright © 2017年 Zheng. All rights reserved.
//

#import "WeAuctionPublishContentCell.h"

#import "WeAuctionPublichTextView.h"

@interface WeAuctionPublishContentCell ()

@property (nonatomic, assign) NSInteger indexIdx;
@property (nonatomic) BOOL isAdd;

@end

@implementation WeAuctionPublishContentCell

#pragma mark - 点击事件
- (void)addImageClickAction:(UIButton *)sender {
    _isAdd = YES;
    _addImageBlock();
}

- (void)setImagesArr:(NSArray<UIImage *> *)imagesArr {
    
    if (_isAdd) {
        
        _imagesArr = imagesArr;
        _addImageBtn.userInteractionEnabled = NO;
        
        if (_cacheViews.count > 0) {
            [_cacheViews enumerateObjectsUsingBlock:^(UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [obj removeFromSuperview];
            }];
        }

        _cancelBtns = [NSMutableArray new];
        _cacheViews = [NSMutableArray new];

        
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        
        __weak typeof(self) weakSelf = self;
        __weak typeof(_imagesArr) weakImageArr = _imagesArr;
        
        dispatch_async(queue, ^{
            [weakImageArr enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [weakSelf uploadImageWithIdx:idx withSemaphore:semaphore];
            }];
        });
        
        NSInteger count = _imagesArr.count;
        CGFloat width = 70/375.f*kSCREEN_WIDTH;
        
        [weakImageArr enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            UIImageView *imgv = [[UIImageView alloc] initWithFrame:(CGRect){15+idx%4*(width+15),200+(width+10)*(idx/4),width,width}];
            imgv.image = obj;
            imgv.userInteractionEnabled = YES;
            [self.contentView addSubview:imgv];
            
            if (idx == 0) {
                UILabel *titleLbl = [[UILabel alloc] initWithFrame:(CGRect){0,55,70,15}];
                titleLbl.backgroundColor = [[UIColor yellowColor] colorWithAlphaComponent:0.8];
                titleLbl.font = kCX_FONT(10);
                titleLbl.text = @"主图";
                titleLbl.textColor = [UIColor blackColor];
                titleLbl.textAlignment = NSTextAlignmentCenter;
                [imgv addSubview:titleLbl];
            }
            
            UIView *maskView = [[UIView alloc] initWithFrame:(CGRect){0,0,70,70}];
            maskView.backgroundColor = [[UIColor darkGrayColor] colorWithAlphaComponent:0.8];
            maskView.tag = 23111+idx;
            [imgv addSubview:maskView];
            
            UILabel *processLbl = [[UILabel alloc] initWithFrame:(CGRect){0,0,70,70}];
            processLbl.font = kCX_FONT(14);
            processLbl.textColor = [UIColor whiteColor];
            processLbl.text = @"0%";
            processLbl.textAlignment = NSTextAlignmentCenter;
            processLbl.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0];
            processLbl.tag = 33111+idx;
            [imgv addSubview:processLbl];
            
            UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            cancelBtn.frame = (CGRect){0,0,20,20};
            cancelBtn.backgroundColor = [UIColor redColor];
            cancelBtn.tag = 43111+idx;
            cancelBtn.userInteractionEnabled = NO;
            [cancelBtn addTarget:self action:@selector(imageCancelClickAction:) forControlEvents:UIControlEventTouchUpInside];
            [imgv addSubview:cancelBtn];
            
            [_cancelBtns addObject:cancelBtn];
            
            [_cacheViews addObject:imgv];
            
        }];
        
        [_addImageBtn mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(15+count%4*(width+15));
            make.bottom.mas_equalTo(-10);
            make.width.height.mas_equalTo(width);
        }];
        
    } else {
        
    }
    
}

#pragma mark - 取消图片点击事件
- (void)imageCancelClickAction:(UIButton *)sender {
    
    _isAdd = NO;
    
    NSMutableArray *newImagesArr = [_imagesArr mutableCopy];
    [newImagesArr removeObjectAtIndex:sender.tag-43111];
    _imagesArr = [newImagesArr copy];
    
    if (_cacheViews.count > 0) {
        [_cacheViews enumerateObjectsUsingBlock:^(UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [obj removeFromSuperview];
        }];
    }
    
    _cancelBtns = [NSMutableArray new];
    _cacheViews = [NSMutableArray new];
    
    NSInteger count = _imagesArr.count;
    CGFloat width = 70/375.f*kSCREEN_WIDTH;
    
    [_imagesArr enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIImageView *imgv = [[UIImageView alloc] initWithFrame:(CGRect){15+idx%4*(width+15),200+(width+10)*(idx/4),width,width}];
        imgv.image = obj;
        imgv.userInteractionEnabled = YES;
        [self.contentView addSubview:imgv];
        
        if (idx == 0) {
            UILabel *titleLbl = [[UILabel alloc] initWithFrame:(CGRect){0,55,70,15}];
            titleLbl.backgroundColor = [[UIColor yellowColor] colorWithAlphaComponent:0.8];
            titleLbl.font = kCX_FONT(10);
            titleLbl.text = @"主图";
            titleLbl.textColor = [UIColor blackColor];
            titleLbl.textAlignment = NSTextAlignmentCenter;
            [imgv addSubview:titleLbl];
        }
        
        UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        cancelBtn.frame = (CGRect){0,0,20,20};
        cancelBtn.backgroundColor = [UIColor redColor];
        cancelBtn.tag = 43111+idx;
        [cancelBtn addTarget:self action:@selector(imageCancelClickAction:) forControlEvents:UIControlEventTouchUpInside];
        [imgv addSubview:cancelBtn];
        
        [_cancelBtns addObject:cancelBtn];
        [_cacheViews addObject:imgv];

    }];
    
    [_addImageBtn mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15+count%4*(width+15));
        make.bottom.mas_equalTo(-10);
        make.width.height.mas_equalTo(width);
    }];
    
    
    _cancelImageBlock(280+(_imagesArr.count/4)*80/375.f*kSCREEN_WIDTH);

}

#pragma mark - 上传图片
- (void)uploadImageWithIdx:(NSInteger)idx withSemaphore:(dispatch_semaphore_t)semaphore {
    UIImage *image = _imagesArr[idx];
    NSData *data = UIImageJPEGRepresentation(image, 0.4);
    NSString *urlStr = @"http://101.200.77.216:8080/kt-app-rest/pic/upload";
    [[AFHTTPSessionManager manager] requestSerializer].timeoutInterval = 10;
    NSDateFormatter *formatter = [NSDateFormatter new];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *fileName = [NSString stringWithFormat:@"%@.jpeg", [formatter stringFromDate:[NSDate date]]];

    if (idx == 0) {
        
        _indexIdx = idx;

        NSURLSessionDataTask *task = [[AFHTTPSessionManager manager] POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/jpeg"];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            [uploadProgress addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew context:nil];
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            kCX_LOG(@"response== %@",responseObject);
            
            [self resetSubviewsWithTag:23111];
            [self resetSubviewsWithTag:33111];
            
            if (_imagesArr.count == 1) {
                _addImageBtn.userInteractionEnabled = YES;
                
                [_cancelBtns enumerateObjectsUsingBlock:^(UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    obj.userInteractionEnabled = YES;
                }];
                                
            } else {
                dispatch_semaphore_signal(semaphore);
            }
            

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            kCX_LOG(@"error == %@",error);
            
            [self resetSubviewsWithTag:23111];
            [self resetSubviewsWithTag:33111];
            
            if (_imagesArr.count == 1) {
                
                _addImageBtn.userInteractionEnabled = YES;
                
                [_cancelBtns enumerateObjectsUsingBlock:^(UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    obj.userInteractionEnabled = YES;
                }];
                
            } else {
                dispatch_semaphore_signal(semaphore);
            }
            

        }];
        
        _tasksBlock(task);

    } else if (idx == _imagesArr.count-1) {
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        _indexIdx = idx;

        NSURLSessionDataTask *task = [[AFHTTPSessionManager manager] POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/jpeg"];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            [uploadProgress addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew context:nil];
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            kCX_LOG(@"response== %@",responseObject);
            
            _addImageBtn.userInteractionEnabled = YES;
            
            [self resetSubviewsWithTag:23111+_indexIdx];
            [self resetSubviewsWithTag:33111+_indexIdx];

            [_cancelBtns enumerateObjectsUsingBlock:^(UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                obj.userInteractionEnabled = YES;
            }];

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
           
            kCX_LOG(@"error == %@",error);
            
            _addImageBtn.userInteractionEnabled = YES;
            
            [self resetSubviewsWithTag:23111+_indexIdx];
            [self resetSubviewsWithTag:33111+_indexIdx];
            
            [_cancelBtns enumerateObjectsUsingBlock:^(UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                obj.userInteractionEnabled = YES;
            }];
        }];
        _tasksBlock(task);

    } else {
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        _indexIdx = idx;

        NSURLSessionDataTask *task = [[AFHTTPSessionManager manager] POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/jpeg"];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            [uploadProgress addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew context:nil];
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            [self resetSubviewsWithTag:23111+_indexIdx];
            [self resetSubviewsWithTag:33111+_indexIdx];
            
            dispatch_semaphore_signal(semaphore);
            
            kCX_LOG(@"response== %@",responseObject);


        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            [self resetSubviewsWithTag:23111+_indexIdx];
            [self resetSubviewsWithTag:33111+_indexIdx];
            
            dispatch_semaphore_signal(semaphore);
            
            kCX_LOG(@"error == %@",error);
            

        }];

        _tasksBlock(task);
    }
}


- (void)resetSubviewsWithTag:(NSInteger)tag {
    UIView *view = [self viewWithTag:tag];
    [view removeFromSuperview];
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    if ([keyPath isEqualToString:@"fractionCompleted"] && [object isKindOfClass:[NSProgress class]]) {
       
        NSProgress *progress = (NSProgress *)object;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            UIView *maskView = [self viewWithTag:23111+_indexIdx];
            maskView.frame = (CGRect){0,progress.fractionCompleted*70,70,70*(1-progress.fractionCompleted)};
            
            UILabel *processLbl = [self viewWithTag:33111+_indexIdx];
            processLbl.text = [NSString stringWithFormat:@"%.0f%%",100*progress.fractionCompleted];

        });
    }
}

#pragma mark - 子视图
- (void)subviewsInContentView {
    [self.contentView addSubview:self.titleTxf];
    [self.contentView addSubview:self.lineView];
    [self.contentView addSubview:self.describeTxtv];
    [self.contentView addSubview:self.addImageBtn];
    
    [_titleTxf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(25);
        make.right.mas_equalTo(-25);
        make.top.mas_equalTo(20);
    }];
    
    [_lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(_titleTxf);
        make.top.equalTo(_titleTxf.mas_bottom).offset(12);
        make.height.mas_equalTo(0.5);
    }];
    
    [_describeTxtv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.right.equalTo(_lineView);
        make.top.equalTo(_lineView.mas_bottom).offset(10);
        make.height.mas_equalTo(120);
    }];
    
    [_addImageBtn mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.bottom.mas_equalTo(-10);
        make.width.height.mas_equalTo(70/375.f*kSCREEN_WIDTH);
    }];

    
    
}

- (UITextField *)titleTxf {
    if (!_titleTxf) {
        _titleTxf = [UITextField new];
        _titleTxf.font = kCX_FONT(14);
        _titleTxf.placeholder = @"发拍的标题";
    }
    return _titleTxf;
}

- (UIView *)lineView {
    if (!_lineView) {
        _lineView = [UIView new];
        _lineView.backgroundColor = kRGB_COLOR(200, 199, 204, 1);
    }
    return _lineView;
}

- (UIButton *)addImageBtn {
    if (!_addImageBtn) {
        _addImageBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_addImageBtn addTarget:self action:@selector(addImageClickAction:) forControlEvents:UIControlEventTouchUpInside];
        _addImageBtn.backgroundColor = [UIColor orangeColor];
    }
    return _addImageBtn;
}

- (WeAuctionPublichTextView *)describeTxtv {
    if (!_describeTxtv) {
        _describeTxtv = [[WeAuctionPublichTextView alloc] init];
        _describeTxtv.top = 5;
    }
    return _describeTxtv;
}

#pragma mark - 初始化方法
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        
        [self subviewsInContentView];
        
        _cacheViews = [NSMutableArray new];
        _cancelBtns = [NSMutableArray new];
        
        
        _isAdd = NO;
    }
    return self;
}

@end
